package project;

import java.io.IOException;
import java.io.Serializable;

import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.SimpleBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

class Looper extends SimpleBehaviour {

	MessageTemplate mt1 = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.INFORM),
			MessageTemplate.MatchSender(new AID("Agent2", AID.ISLOCALNAME)));

	static String offset = "";
	static long t0 = System.currentTimeMillis();

	Agent agent;
	String tab = "";
	int n = 1;
	long dt;

	public Looper(Agent a, long dt) {
		super(a);
		this.agent = a;
		this.dt = dt;
		offset += "    ";
		tab = new String(offset);
	}

	public void action() {

		if (Ag12.bool) {
			CitesteDinBazaDeDate();
		} else {
			ACLMessage msg = Ag12.mesaj;
			if (msg == null) {
				ACLMessage msg1 = agent.blockingReceive(mt1, 4000);

				System.out.println(tab + (System.currentTimeMillis() - t0) / 10 * 10 + ": " + myAgent.getLocalName());

				ACLMessage msgToSend = new ACLMessage(ACLMessage.INFORM);
				try {
					msgToSend.setContentObject((Serializable) new Reader().readData());
				} catch (IOException e) {
					System.out.println("Exception in Agent1");
					e.printStackTrace();
				}

				msgToSend.addReceiver(new AID("Agent2", AID.ISLOCALNAME));

				Ag12.mesaj = msgToSend;
				agent.send(msgToSend);

				n++;
			} else {
				agent.doWait(8000);
			}
			block();
		}
		block(6000);
	}

	private void CitesteDinBazaDeDate() {
		Reader citeste = new Reader();
		Ag12.ListaValori = citeste.readData();
	}

	public boolean done() {
		return false;
	}

}
